import {
  SET_TGT_TOKEN,
  SET_TOKEN,
  SET_USER_HOW_TO_LOGIN,
  SET_USER_INFO, SET_USER_OPEN_ID
} from '../store/types'
import store from '@/store'
import { accountUserInfo } from '@/api/login'
import { msg } from '@/utils/tools'
import { THREE_PART_LOGIN_DATA, USER_INFO, OPENID } from '../utils/storageTypes'
import { useLogin } from '@/hooks/hooks'
import { uniapp } from '@/utils/uni'
// import { getOpenid } from '@/api/auth'

export const useClearUserInfo = () => {
  const userKeys = [
    'userInfo',
    'threePartLoginData',
    'publicKeyExpireTime',
    'publicKey',
    'token',
    'token_expirationTime'
  ]
  userKeys.map((key) => uni.removeStorageSync(key))
  store.commit(`user/${SET_TGT_TOKEN}`, '')
  store.commit(`user/${SET_USER_INFO}`, '')
  store.commit(`user/${SET_TOKEN}`, '')
}

export const getUserInfo = async () => {
  if (!uni.getStorageSync(THREE_PART_LOGIN_DATA)) {
    return useLogin()
  }
  const tgt = uni.getStorageSync(THREE_PART_LOGIN_DATA).tgt
  try {
    const { data, code, msg: message } = await accountUserInfo(tgt)
    if (code !== 200) {
      return msg('用户信息获取失败:' + message)
    }

    let userInfo = uni.getStorageSync(USER_INFO) || {}

    userInfo = {
      ...userInfo,
      ...data,
    }

    uni.setStorageSync(USER_INFO, userInfo)
    store.commit(`user/${SET_USER_INFO}`, { ...userInfo, ...data })
    return Promise.resolve(userInfo)
  } catch (e) {
    //TODO handle the exception
    return Promise.reject(null)
  }
}

// 获取openid
// export const useOpenId = async () => {
//   let openid = uni.getStorageSync(OPENID) || ''
//   try {
//     if (!openid) {
//       const { code } = await uniapp('login')
//       const { data } = await getOpenid({ code })
//       if (data.openid) {
//         openid = data.openid
//         uni.setStorageSync(OPENID, data.openid)
//       }
//     }
//   } catch (e) {
//     //TODO handle the exception
//   }
//   return { openid }
// }
